package net.fpeg.kotlin.msa.wordbase.controller

import net.fpeg.kotlin.msa.wordbase.dto.WordSentenceDto
import net.fpeg.kotlin.msa.wordbase.dto.WordSentenceIndexDto
import net.fpeg.kotlin.msa.wordbase.service.WordSentenceService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.domain.Pageable
import org.springframework.http.HttpStatus
import org.springframework.web.bind.annotation.*


@RestController
@RequestMapping("/wordSentence")
class WordSentenceController {
    @Autowired
    lateinit var wordSentenceService: WordSentenceService

    /**
     * 根据来源id找出所有例句
     */
    @GetMapping("/{sourceId}")
    fun fetch(
            @RequestHeader("USER_ID") uid: Long,
            @PathVariable("sourceId") sourceId: Long,
            pageable: Pageable): WordSentenceDto = wordSentenceService.find(uid, sourceId, pageable).run {
        WordSentenceDto(
                this.size,
                this.map {
                    it.run {
                        WordSentenceIndexDto(id ?: throw Exception("未知错误"), englishValue, chineseValue, "", sourceId)
                    }
                }
        )
    }

    /**
     * 根据单词和来源id找出所有包含此单词的例句
     */
    @GetMapping("/{sourceId}/{wordValue}")
    fun fetch(
            @RequestHeader("USER_ID") uid: Long,
            @PathVariable("sourceId") sourceId: Long,
            @PathVariable("wordValue") wordValue: String,
            pageable: Pageable
    ): WordSentenceDto =
            wordSentenceService.find(uid, sourceId, wordValue, pageable)
                    .map {
                        it.run {
                            WordSentenceIndexDto(
                                    id ?: throw Exception("未知错误"), englishValue, chineseValue, "", wordSource.id
                                    ?: throw Exception("空来源错误")
                            )
                        }
                    }.run { WordSentenceDto(size, this) }

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    fun add(
            @RequestHeader("USER_ID") id: Long,
            @RequestBody wordSentenceIndexDto: WordSentenceIndexDto
    ) =
            wordSentenceService.add(id, wordSentenceIndexDto).id

    @PutMapping
    @ResponseStatus(HttpStatus.NO_CONTENT)
    fun edit(
            @RequestHeader("USER_ID") id: Long,
            @RequestBody wordSentenceIndexDto: WordSentenceIndexDto
    ) {
        wordSentenceService.edit(id, wordSentenceIndexDto)
    }

    @DeleteMapping("/{sentenceId}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    fun remove(
            @RequestHeader("USER_ID") id: Long,
            @PathVariable("sentenceId") sentenceId: Long
    ) {
        wordSentenceService.remove(id, sentenceId)
    }


}